package cn.elead.chaos.remote.exception;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.elead.chaos.api.enums.ExStatus;
import cn.elead.chaos.api.web.IExceptionResolverService;
import cn.elead.chaos.framework.util.ResponseUtils;
import cn.elead.chaos.framework.web.global.ErrorCodeEnum;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import feign.FeignException;
import lombok.extern.slf4j.Slf4j;

/**
 * 自定义异常处理
 * <p>
 * https://blog.csdn.net/weixin_39520967/article/details/99706639<br>
 * https://www.jianshu.com/p/cf1278d687e4<br>
 * https://blog.csdn.net/wj123446/article/details/77873661<br>
 * https://blog.csdn.net/qq_34178998/article/details/89326254<br>
 * 
 */
@Slf4j
public class FeignExceptionResolverService implements IExceptionResolverService {

	@Override
	public ExStatus doException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex, Object view) {
		if (ex instanceof FeignException) {
			log.error(ex.getMessage(), ex);
			String subBetween = StrUtil.subBetween(ex.getMessage(), "[{", "}]");
			JSONObject message = JSONUtil.parseObj("{" + subBetween + "}");
			ResponseUtils.sendFail(request, response, ErrorCodeEnum.BAD_REQUEST.convert(message.getStr("msg")), ex);
			return ExStatus.HIT;
		}
		return ExStatus.SKIP;
	}

}
